package com.wenzhoujie.fragment;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.sunday.eventbus.SDEventManager;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;
import com.wenzhoujie.CollectionTuanGoodsActivity;
import com.wenzhoujie.DeliveryAddressActivty;
import com.wenzhoujie.EnterApplayActivity;
import com.wenzhoujie.FrequentedGoActivity;
import com.wenzhoujie.ModifyPasswordActivity;
import com.wenzhoujie.MoreSetupActivity;
import com.wenzhoujie.MyCouponListActivity;
import com.wenzhoujie.MyEventListActivity;
import com.wenzhoujie.MyOrderListActivity;
import com.wenzhoujie.MyYouhuiListActivity;
import com.wenzhoujie.RemindActivity;
import com.wenzhoujie.SubscribeActivity;
import com.wenzhoujie.WebViewActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.common.CommonInterface;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.wenzhoujie.model.CartGoodsArrayList;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.My_accountActModel;
import com.wenzhoujie.model.act.SyncbindActModel;
import com.wenzhoujie.umeng.UmengSocialManager;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

/**
 * 我的账户fragment
 * 
 * @author js02
 * 
 */
public class MyAccountFragment extends BaseFragment implements OnClickListener {
	@ViewInject(id = R.id.frag_my_account_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	@ViewInject(id = R.id.frag_my_account_tv_username)
	private TextView mTvUsername = null; // 用户名

	@ViewInject(id = R.id.frag_my_account_tv_balance)
	private TextView mTvBalance = null; // 账户余额

	@ViewInject(id = R.id.frag_my_account_tv_user_score)
	private TextView mTv_user_score = null;// 积分

	@ViewInject(id = R.id.frag_my_account_ll_group_voucher)
	private LinearLayout mLlGroupVoucher = null;

	@ViewInject(id = R.id.frag_my_account_tv_group_voucher)
	private TextView mTvGroupVoucher = null; // 我的团购券数量

	@ViewInject(id = R.id.frag_my_account_ll_group_coupons)
	private LinearLayout mLlGroupCoupons = null;

	@ViewInject(id = R.id.frag_my_account_tv_coupons)
	private TextView mTvCoupons = null; // 我的优惠券数量

	@ViewInject(id = R.id.frag_my_account_rl_not_payorder)
	private View mRlNotPayorder = null; // 待付款订单

	@ViewInject(id = R.id.frag_my_account_tv_nopayment_count)
	private TextView mTvNopaymentCount = null;// 待付款订单数量

	@ViewInject(id = R.id.frag_my_account_rl_payorder)
	private View mRlPayorder = null; // 已付款订单

	@ViewInject(id = R.id.frag_my_account_btn_payorder_uncomment)
	private Button mBtnPayorderUncomment = null; // 评价已付款订单

	@ViewInject(id = R.id.frag_my_account_ll_my_event)
	private View mLlMyEvent = null; // 配送地址

	@ViewInject(id = R.id.frag_my_account_rl_delivery_address)
	private View mRlDeliveryAddress = null; // 配送地址

	@ViewInject(id = R.id.frag_my_account_rl_oftengo_place)
	private View mRlOftengoPlace = null; // 常去地点

	@ViewInject(id = R.id.frag_my_account_rl_subscribe)
	private View mRlSubscribe = null; // 订阅

	@ViewInject(id = R.id.frag_my_account_rl_shopping_cart)
	private View mShopping_cart = null;// 购物车

	@ViewInject(id = R.id.frag_my_account_tv_shopping_cart_num)
	private TextView mTv_shopping_cart_num;// 购物车数量

	@ViewInject(id = R.id.frag_my_account_rl_collect)
	private View mRlCollect = null; // 收藏

	@ViewInject(id = R.id.frag_my_account_rl_subscribe_message)
	private View mRlSubscribeMessage = null; // 消息提醒

	@ViewInject(id = R.id.frag_my_account_rl_sinablog_binding)
	private View mRlSinablogBinding = null; // 绑定新浪微博

	@ViewInject(id = R.id.frag_my_account_rl_QQbind)
	private View mRlQqbind = null; // 绑定qq

	@ViewInject(id = R.id.frag_my_account_rl_change_password)
	private View mRlChangePassword = null; // 修改密码

	@ViewInject(id = R.id.frag_my_account_btn_logout)
	private Button mBtnLogout = null; // 退出帐号

	private MoreFragment mFragMore;
	private BaseFragment mFragLast = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_my_account, container, false);
		view = setmTitleType(TitleType.TITLE_SIMPLE, view);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init() {
		initTitle();
		registeClick();
		// initViewState();
		initPullToRefreshScrollView();

	}

	private void initViewState() {
		String sinaAppKey = AppRuntimeWorker.getSina_app_key();
		String qqAppKey = AppRuntimeWorker.getQq_app_key();
		if (TextUtils.isEmpty(sinaAppKey)) {
			mRlSinablogBinding.setVisibility(View.GONE);
		}
		if (TextUtils.isEmpty(qqAppKey)) {
			mRlQqbind.setVisibility(View.GONE);
		}

	}

	private void initPullToRefreshScrollView() {
		mPtrsvAll.setMode(Mode.PULL_FROM_START);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
				requestMyAccount();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			}

		});
		mPtrsvAll.setRefreshing();
	}

	/**
	 * 请求我的账户接口
	 */
	public void requestMyAccount() {
		if (AppHelper.getLocalUser() != null) {
			RequestModel model = new RequestModel();
			model.put("act", "my_account");
			model.put("email", AppHelper.getLocalUser().getUser_name());
			model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			// System.out.println("my_account:email"+AppHelper.getLocalUser().getUser_name()+"pwd"+AppHelper.getLocalUser().getUser_pwd());
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {

				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					System.out.println("responseInfo.result" + responseInfo.result);
					My_accountActModel actModel = JsonUtil.json2Object(responseInfo.result, My_accountActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							bindData(actModel);
						} else {
							mTvNopaymentCount.setVisibility(View.GONE);
							CommonInterface.refreshLocalUser();
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					mTvNopaymentCount.setVisibility(View.GONE);
				}

				@Override
				public void onFinish() {
					mPtrsvAll.onRefreshComplete();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	protected void bindData(My_accountActModel actModel) {
		// if(actModel.getNick_name()!="" || actModel.getNick_name()!=null)
		{
			SDViewBinder.setTextView(mTvUsername, actModel.getNick_name(), actModel.getUser_name());
		}
		// else
		// {
		// SDViewBinder.setTextView(mTvUsername, actModel.getUser_name(),
		// "未找到");
		// }

		SDViewBinder.setTextView(mTvBalance, actModel.getUser_money_format(), "未找到");
		SDViewBinder.setTextView(mTv_user_score, actModel.getUser_score(), "未找到");

		SDViewBinder.setTextView(mTvGroupVoucher, actModel.getCoupon_count(), "未找到");
		SDViewBinder.setTextView(mTvCoupons, actModel.getYouhui_count(), "未找到");

		SDViewBinder.setTextViewsVisibility(mTvNopaymentCount, actModel.getNot_pay_order_count());
	}

	private void initTitle() {
		mTitleSimple.setmListener(new SDTitleSimpleListener() {

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v) {
				// TODO Auto-generated method stub MoreSetupActivity
				Intent intent = new Intent(App.getApplication(), MoreSetupActivity.class);
				startActivity(intent);
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v) {
				// TODO Auto-generated method stub

			}
		});
		mTitleSimple.setLeftLayoutVisibility(View.GONE);
		mTitleSimple.setTitleTop("我的");

		mTitleSimple.setRightLayoutBackground(R.drawable.ttsettings);
	}

	private void registeClick() {
		mLlGroupVoucher.setOnClickListener(this);
		mLlGroupCoupons.setOnClickListener(this);
		mRlNotPayorder.setOnClickListener(this);
		mRlPayorder.setOnClickListener(this);
		mBtnPayorderUncomment.setOnClickListener(this);
		mLlMyEvent.setOnClickListener(this);
		mRlDeliveryAddress.setOnClickListener(this);
		mRlOftengoPlace.setOnClickListener(this);
		mRlSubscribe.setOnClickListener(this);
		mShopping_cart.setOnClickListener(this);
		mRlCollect.setOnClickListener(this);
		mRlSubscribeMessage.setOnClickListener(this);
		mRlSinablogBinding.setOnClickListener(this);
		mRlQqbind.setOnClickListener(this);
		mRlChangePassword.setOnClickListener(this);
		mBtnLogout.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.frag_my_account_ll_group_voucher:
			clickGroupVoucher(); // 我的团购券数量
			break;

		case R.id.frag_my_account_ll_group_coupons:
			clickGoupCoupons(); // 我的优惠券数量
			break;

		case R.id.frag_my_account_rl_not_payorder:
			clickNotPayorder(); // 待付款订单
			break;

		case R.id.frag_my_account_rl_payorder:
			clickPayorder(); // 已付款订单
			break;

		case R.id.frag_my_account_btn_payorder_uncomment:
			clickPayorderUncomment(); // 已付款为评价订单
			break;

		case R.id.frag_my_account_ll_my_event:
			clickMyEvent(); // 我的活动
			break;

		case R.id.frag_my_account_rl_delivery_address:
			clickDeliveryAddress(); // 配送地址
			break;

		case R.id.frag_my_account_rl_oftengo_place:
			clickOftengoPlace(); // 常去地点
			break;

		case R.id.frag_my_account_rl_subscribe:
			clickSubscribe();// 订阅
			break;

		case R.id.frag_my_account_rl_shopping_cart:
			// clickShopping_cart();// 购物车
			clickEnterApplay();//入驻申请
			break;

		case R.id.frag_my_account_rl_collect:
			clickCollect(); // 收藏
			break;
		case R.id.frag_my_account_rl_subscribe_message:
			clickSubscribeMessage(); // 消息提醒
			break;

		case R.id.frag_my_account_rl_sinablog_binding:
			clickSinablogBinding(); // 绑定新浪微博
			break;

		case R.id.frag_my_account_rl_QQbind:
			clickQQBinding(); // 绑定qq
			break;

		case R.id.frag_my_account_rl_change_password:
			clickChangePassword();// 修改密码
			break;

		case R.id.frag_my_account_btn_logout:
			clickLogout(); // 退出当前帐号
			break;

		default:
			break;
		}
	}

	/**
	 * 我的团购券
	 */
	private void clickGroupVoucher() {
		startActivity(new Intent(getActivity(), MyCouponListActivity.class));
	}

	/**
	 * 我的优惠券
	 */
	private void clickGoupCoupons() {
		startActivity(new Intent(getActivity(), MyYouhuiListActivity.class));
	}

	/**
	 * 未付款订单
	 */
	private void clickNotPayorder() {
		Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
		intent.putExtra(MyOrderListActivity.EXTRA_PAY_STATUS, 0);
		startActivity(intent);
	}

	/**
	 * 已付款订单
	 */
	private void clickPayorder() {
		Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
		intent.putExtra(MyOrderListActivity.EXTRA_PAY_STATUS, 2);
		startActivity(intent);
	}

	private void clickPayorderUncomment() {

	}

	/**
	 * 我的活动
	 */
	private void clickMyEvent() {
		Intent intent = new Intent(getActivity(), MyEventListActivity.class);
		startActivity(intent);
	}

	/**
	 * 配送地址
	 */
	private void clickDeliveryAddress() {
		Intent intent = new Intent(getActivity(), DeliveryAddressActivty.class);
		intent.putExtra(DeliveryAddressActivty.EXTRA_DELIVERY_MODE, "1");
		startActivity(intent);
	}

	/**
	 * 常去地点
	 */
	private void clickOftengoPlace() {
		startActivity(new Intent(getActivity(), FrequentedGoActivity.class));
	}

	/**
	 * 订阅
	 */
	private void clickSubscribe() {
		startActivity(new Intent(getActivity(), SubscribeActivity.class));
	}
	
	/**
	 * 入驻申请
	 */
	private void clickEnterApplay() {
		startActivity(new Intent(getActivity(), EnterApplayActivity.class));
	}

	/**
	 * 购物车
	 */
	private void clickShopping_cart() {
		// startActivity(new Intent(getActivity(), ShopCartActivity.class));
		LocalUserModel userModel = App.getApplication().getmLocalUser();

		/*
		 * 首页的“外卖宵夜”接口地址和个人中心页的“我的餐车”地址，都加上un和uid参数，
		 * 如果用户是登录状态这两个参数值就分别是用户名和用户id， 如果不是登陆状态这两个参数值就是空。
		 */

		String uname = "";
		String upw = "";
		if (userModel != null) {
			uname = userModel.getUser_name();
			upw = userModel.getUser_pwd();
			// uid = userModel.getUser_id();
		}
		String JCUrl = ApkConstant.SERVER_URL + "/dc/index.php?m=wap&c=company&f=cart&from=app&un=" + uname + "&upw="
				+ upw;

		System.out.println("JCURL: " + JCUrl);

		Intent intent = new Intent(App.getApplication(), WebViewActivity.class);
		intent.putExtra(WebViewActivity.EXTRA_URL, JCUrl);
		startActivity(intent);
	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	/**
	 * 收藏
	 */
	private void clickCollect() {
		startActivity(new Intent(getActivity(), CollectionTuanGoodsActivity.class));
	}

	/**
	 * 消息提醒
	 */
	private void clickSubscribeMessage() {
		startActivity(new Intent(getActivity(), RemindActivity.class));
	}

	/**
	 * 点击绑定新浪微博，先授权，后绑定
	 */
	private void clickSinablogBinding() {
		UmengSocialManager.getUMLogin().doOauthVerify(getActivity(), SHARE_MEDIA.SINA, new UMAuthListener() {

			@Override
			public void onStart(SHARE_MEDIA arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(SocializeException arg0, SHARE_MEDIA arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(Bundle bundle, SHARE_MEDIA arg1) {
				String uid = bundle.getString("uid");
				String expires_in = bundle.getString("expires_in");
				String access_token = bundle.getString("access_secret");
				if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(expires_in) && !TextUtils.isEmpty(access_token)) {
					// TODO 绑定新浪微博
					requestBindSinaWeibo(uid, access_token);
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 绑定新浪微博
	 * 
	 * @param uid
	 * @param expires_in
	 * @param access_token
	 */
	protected void requestBindSinaWeibo(String uid, String access_token) {
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (user != null) {
			RequestModel model = new RequestModel();
			model.put("act", "syncbind");
			model.put("login_type", "USSina");
			model.put("email", user.getUser_name());
			model.put("pwd", user.getUser_pwd());
			model.put("type", "android");
			model.put("sina_id", uid);
			model.put("access_token", access_token);
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					SyncbindActModel actModel = JsonUtil.json2Object(responseInfo.result, SyncbindActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							// 绑定成功，服务器会返回提示信息，用toast显示即可，不用另外显示
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	/**
	 * 绑定腾讯qq，先授权,后绑定
	 */
	private void clickQQBinding() {
		UmengSocialManager.getUMLogin().doOauthVerify(getActivity(), SHARE_MEDIA.QQ, new UMAuthListener() {

			@Override
			public void onStart(SHARE_MEDIA arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(SocializeException arg0, SHARE_MEDIA arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(Bundle bundle, SHARE_MEDIA arg1) {
				String openId = bundle.getString("openid");
				String expires_in = bundle.getString("expires_in");
				String access_token = bundle.getString("access_token");
				if (!TextUtils.isEmpty(openId) && !TextUtils.isEmpty(expires_in) && !TextUtils.isEmpty(access_token)) {
					// TODO 绑定QQ
					requestBindTencentQQ(openId, access_token);
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 绑定腾讯QQ
	 * 
	 * @param uid
	 * @param expires_in
	 * @param access_token
	 */
	protected void requestBindTencentQQ(String openid, String access_token) {
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (user != null) {
			RequestModel model = new RequestModel();
			model.put("act", "syncbind");
			model.put("login_type", "Qq");
			model.put("email", user.getUser_name());
			model.put("pwd", user.getUser_pwd());
			model.put("type", "android");
			model.put("openid", openid);
			model.put("access_token", access_token);
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					SyncbindActModel actModel = JsonUtil.json2Object(responseInfo.result, SyncbindActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							// 绑定成功，服务器会返回提示信息，用toast显示即可，不用另外显示
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	private void clickChangePassword() {
		startActivity(new Intent(getActivity(), ModifyPasswordActivity.class));
	}

	private void clickLogout() {
		SDEventManager.post(EnumEventTag.LOGOUT.ordinal());
	}

	@Override
	public void onEventMainThread(SDBaseEvent event) {
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		if (event.getEventTagInt() == EnumEventTag.REFRESH_USER_MONEY_SUCCESS.ordinal()) {
			SDViewBinder.setTextView(mTvUsername, AppHelper.getLocalUser().getUser_name());
			SDViewBinder.setTextView(mTvBalance, AppHelper.getLocalUser().getUser_money_format());
			SDViewBinder.setTextView(mTv_user_score, AppHelper.getLocalUser().getUser_score());
		}
	}

	@Override
	public void onResume() {
		CartGoodsArrayList cartlist = App.getApplication().getListCartGoodsModel();
		if (cartlist != null) {
			if (cartlist.size() > 0) {
				// mTv_shopping_cart_num.setVisibility(View.VISIBLE);
				// mTv_shopping_cart_num.setText(cartlist.size() + "");
			} else {
				mTv_shopping_cart_num.setVisibility(View.GONE);
			}

		}

		super.onResume();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			mPtrsvAll.setRefreshing();
		}
	}

}